package cn.xorange.commons.utils.poi.excel;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.xorange.commons.utils.exception.UtilsException;
import cn.xorange.commons.utils.poi.excel.handler.ExcelDictHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFDataValidationHelper;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * @program: la-2.0
 * @description:
 * @author: gonghe
 * @create: 2021-03-08 14:27
 */
public class EasyExcelUtil {

    private EasyExcelUtil() {
    }


    /**
     * excel 导出
     *
     * @param list           数据
     * @param title          标题
     * @param sheetName      sheet名称
     * @param pojoClass      pojo类型
     * @param fileName       文件名称
     * @param isCreateHeader 是否创建表头
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws IOException {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        exportParams.setStyle(ExcelStyleUtil.class);
        exportParams.setHeight((short) 6);
        exportParams.setCreateHeadRows(isCreateHeader);
        exportParams.setDictHandler(new ExcelDictHandler());
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * excel 导出
     *
     * @param list      数据
     * @param title     标题
     * @param sheetName sheet名称
     * @param pojoClass pojo类型
     * @param fileName  文件名称
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        exportParams.setStyle(ExcelStyleUtil.class);
        exportParams.setHeight((short) 6);
        exportParams.setDictHandler(new ExcelDictHandler());
        try {
            defaultExport(list, pojoClass, fileName, response, exportParams);
        }catch (IOException e){
            throw UtilsException.systemException(e.getMessage());
        }

    }

    /**
     * excel 导出
     *
     * @param dataList   数据
     * @param title      标题
     * @param sheetName  sheet名称
     * @param entityList 自定义数据类型
     * @param fileName   文件名称
     * @param response
     */
    public static void exportCustomizeExcel(String fileName, String title, String sheetName, List<ExcelExportEntity> entityList, List<Map<String, Object>> dataList, HttpServletResponse response) throws IOException {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        exportParams.setStyle(ExcelStyleUtil.class);
        exportParams.setHeight((short) 6);
        exportParams.setDictHandler(new ExcelDictHandler());
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, entityList, dataList);
        downLoadExcel(fileName, response, workbook);
    }


    /**
     * excel 导出
     *
     * @param list         数据
     * @param pojoClass    pojo类型
     * @param fileName     文件名称
     * @param response
     * @param exportParams 导出参数
     */
    public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) throws IOException {
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * excel 导出
     *
     * @param list     数据
     * @param fileName 文件名称
     * @param response
     */
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
        defaultExport(list, fileName, response);
    }

    /**
     * 默认的 excel 导出
     *
     * @param list         数据
     * @param pojoClass    pojo类型
     * @param fileName     文件名称
     * @param response
     * @param exportParams 导出参数
     */
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * 默认的 excel 导出
     *
     * @param list     数据
     * @param fileName 文件名称
     * @param response
     */
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * 下载
     *
     * @param fileName 文件名称
     * @param response
     * @param workbook excel数据
     */
    public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 导入
     *
     * @param filePath   excel文件路径
     * @param titleRows  标题行
     * @param headerRows 表头行
     * @param pojoClass  pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
        if (StringUtils.isBlank(filePath)) {
            return new ArrayList<>();
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
//        params.setDictHandler(new ExcelDictHandler());
        params.setNeedSave(false);
//        params.setSaveUrl("/excel/");
        try {
            return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("模板不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * excel 导入
     *
     * @param file      excel文件
     * @param pojoClass pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws IOException {
        return importExcel(file, 1, 1, pojoClass);
    }


    /**
     * excel 导入
     *
     * @param file       excel文件
     * @param titleRows  标题行
     * @param headerRows 表头行
     * @param pojoClass  pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
        return importExcel(file, titleRows, headerRows, false, pojoClass);
    }

    /**
     * excel 导入
     *
     * @param file       上传的文件
     * @param titleRows  标题行
     * @param headerRows 表头行
     * @param needVerfiy 是否检验excel内容
     * @param pojoClass  pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, boolean needVerfiy, Class<T> pojoClass) throws IOException {
        if (file == null) {
            return new ArrayList<>();
        }
        try {
            return importExcel(file.getInputStream(), titleRows, headerRows, needVerfiy, pojoClass);
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }


    /**
     * 读取动态列Excel数据
     *
     * @param inputStream 导入文件流
     * @param titleRows   标题行数
     * @param headerRows  列头行数
     * @param needVerfiy  是否需要校验
     * @return java.util.List<java.lang.Object>
     * @author gonghe
     * @date 2021/7/12 9:43
     */
    public static List<Object> importCustomizeExcel(InputStream inputStream, Integer titleRows, Integer headerRows, boolean needVerfiy) throws IOException {
        if (inputStream == null) {
            return new ArrayList<>();
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setDictHandler(new ExcelDictHandler());
//        params.setSaveUrl("/home/zkgl/apps/la/upload/");
        params.setNeedSave(false);
        params.setNeedVerify(needVerfiy);
        try {
            return ExcelImportUtil.importExcel(inputStream, Map.class, params);
        } catch (NoSuchElementException e) {
            throw new IOException("excel文件不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }


    /**
     * excel 导入
     *
     * @param inputStream 文件输入流
     * @param titleRows   标题行
     * @param headerRows  表头行
     * @param needVerfiy  是否检验excel内容
     * @param pojoClass   pojo类型
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, boolean needVerfiy, Class<T> pojoClass) throws IOException {
        if (inputStream == null) {
            return new ArrayList<>();
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setDictHandler(new ExcelDictHandler());
//        params.setSaveUrl("/home/zkgl/apps/la/upload/");
        params.setNeedSave(false);
        params.setNeedVerify(needVerfiy);
        try {
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("excel文件不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * 获取自定义workbook对象
     *
     * @param title      标题
     * @param sheetName  sheet名称
     * @param entityList 自定义数据类型
     * @param dataList   列数据
     * @return org.apache.poi.ss.usermodel.Workbook
     * @author gonghe
     * @date 2021/7/6 17:49
     */
    public static Workbook getCustomizeWorkbook(String title, String sheetName, List<ExcelExportEntity> entityList, List<Map<String, Object>> dataList) {
        ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        exportParams.setStyle(ExcelStyleUtil.class);
        exportParams.setHeight((short) 6);
        exportParams.setDictHandler(new ExcelDictHandler());
        return ExcelExportUtil.exportExcel(exportParams, entityList, dataList);
    }

    /**
     * @param wb        Workbook
     * @param dataArray 下拉内容
     * @param firstRow  开始行号(下标0开始)
     * @param lastRow   结束行号，最大65535
     * @param firstCol  区域中第一个单元格的列号 (下标0开始)
     * @param lastCol   区域中最后一个单元格的列号
     * @return void
     * @author gonghe
     * @date 2021/7/8 11:36
     */
    public static void setXSSFValidation(Workbook wb, String[] dataArray, int firstRow, int lastRow, int firstCol, int lastCol) {

        Sheet sheet = wb.getSheetAt(0);
        // 创建sheet，写入枚举项
        Sheet hideSheet = wb.createSheet("hiddenSheet" + firstCol);
        for (int i = 0; i < dataArray.length; i++) {
            hideSheet.createRow(i)
                     .createCell(0)
                     .setCellValue(dataArray[i]);
        }

        DataValidationHelper helper = new XSSFDataValidationHelper((XSSFSheet) hideSheet);
        if (dataArray.length > 0) {
            DataValidationConstraint constraint = helper.createFormulaListConstraint("hiddenSheet" + firstCol +
                    "!" + "$A$1:$A$" + dataArray.length);
            // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
            CellRangeAddressList regions = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
            // 数据有效性对象
            DataValidation dataValidation = helper.createValidation(constraint, regions);
            // 处理Excel兼容性问题
            if (dataValidation instanceof XSSFDataValidation) {
                dataValidation.setSuppressDropDownArrow(true);
                dataValidation.setShowErrorBox(true);
            } else {
                dataValidation.setSuppressDropDownArrow(false);
            }

            sheet.addValidationData(dataValidation);
        }
        wb.setSheetHidden(wb.getSheetIndex(hideSheet), true);
    }

}
